package com.cloudansys.core.util;

import com.cloudansys.core.constant.Const;
import com.cloudansys.core.entity.MultiDataEntity;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class PayloadParseUtil {

    /**
     * 解析原始数据，封装成 List<MultiDataEntity> 对象
     *      原始流中元素{项目id,时间（17位字符串）,功能码,测点类型,预留字节,测定个数,指标个数,测定id,value}
     *      {项目id,时间（17位字符串）,测定类型,测定个数，指标个数，id，value}
     * 返回：List<MultiDataEntity>
     */
    public static List<MultiDataEntity> parsePayload(String payload) {
        long start = System.nanoTime();
        List<MultiDataEntity> multiDataEntities = new ArrayList<>();
        int sensorNum, typeCode, quotaNum;
        String projectId, targetType, pickTime;
        String[] items = payload.split(Const.COMMA);
        int elementSize = items.length;
        // 判断是否是有效元素【1、基本信息】
        if (elementSize < 7) {
            return null;
        }

        // 解析出基本信息
        int index = 0;
        projectId = items[index++];
        pickTime = items[index++];
        index++; // 功能码
        typeCode = Integer.parseInt(items[index++]); // 测点类型编号
        targetType = Const.TARGET_TYPE_CODE.get(typeCode);
        index++; // 预留字节
        sensorNum = Integer.parseInt(items[index++]);
        quotaNum = Integer.parseInt(items[index]);

        // 判断是否是有效元素【2、数据信息】
        int valueSize = sensorNum * (quotaNum + 1);
//        log.info("elementSize: {}", elementSize);
//        log.info("valueSize: {}", valueSize);
        if (elementSize != (7 + valueSize)) {
            return null;
        }

        // 将数值拷贝成一个新数组  a1,aq1,aq2,aq3,b1,bq1,bq2,bq3,c1,cq1,cq2,cq3,...
        String[] keyValues = Arrays.copyOfRange(items, 7, elementSize);
        for (int i = 0; i < sensorNum; i++) {
            int indexOfSerialCode = i * (quotaNum + 1);
            MultiDataEntity multiDataEntity = new MultiDataEntity();
            String serialCode = keyValues[indexOfSerialCode];
            multiDataEntity.setProjectId(projectId);
            multiDataEntity.setSerialCode(serialCode);
            multiDataEntity.setTargetType(targetType);
            multiDataEntity.setPickTime(pickTime);
            Double[] values = new Double[quotaNum];
            int indexOfFirstQuota = indexOfSerialCode + 1;
            int indexOfLastQuota = indexOfSerialCode + quotaNum;
            for (int j = indexOfFirstQuota; j <= indexOfLastQuota; j++) {
                values[j - indexOfFirstQuota] = Double.parseDouble(keyValues[j]);
            }
            multiDataEntity.setValues(values);
            multiDataEntity.setCount(1);
            multiDataEntities.add(multiDataEntity);
        }
        long end = System.nanoTime();
//        log.info("耗时：{}", end - start);
        return multiDataEntities;
    }
}
